package com.epoint.mobileoa.ui.sysconfig;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

import com.epoint.mobileoa.R;
import com.epoint.mobileoa.bizlogic.ConfigKey;
import com.epoint.mobileoa.bizlogic.FrameMethod;
import com.epoint.mobileoa.bizlogic.Res;
import com.epoint.mobileoa.bizlogic.SuperView;
import com.epoint.mobileoa.bizlogic.Task;
import com.epoint.mobileoa.bizlogic.mobileoa.TestConnectionTask;
import com.epoint.mobileoa.db.DBHelp;
import com.epoint.mobileoa.service.MainService;
import com.epoint.mobileoa.tools.AlertHelp;
import com.epoint.mobileoa.tools.ControlsHelp;
import com.epoint.mobileoa.tools.MusicHelp;
import com.epoint.mobileoa.tools.PropertiesHelp;
import com.epoint.mobileoa.tools.StringHelp;
import com.epoint.mobileoa.tools.ToastHelp;
import com.epoint.mobileoa.tools.dialog.SuperDialog;
import com.epoint.mobileoa.ui.init.InitView;
import com.epoint.mobileoa.ui.mail.MailSendView;
import com.epoint.mobileoa.ui.main.MainView;
import com.epoint.mobileoa.ui.statistics.StatisticsMain;
import com.epoint.mobileoa.ui.update.UpdateView;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author liyc
 * @time 2012-1-10 上午12:56:06
 * @annotation 系统设置
 */
public class SysconfigView extends SuperView {

	public static final int TestConnection = 1;//测试连接

	private ListView lv;
	private String[] arr = new String[]{"服务器设置","主题设置","登录配置","全屏切换","消息提示音","软件初始化","图标排序","显示类型","问题反馈","考勤签到","主界面样式"};
	private String[] themes = new String[]{"红白色调","经典蓝色"};
	private String[] displayTypeArr = new String[]{"网格","分屏"};

	private List<SettingListModel> slist = new ArrayList<SettingListModel>();
	private SuperView sv;
	@Override
	public void initControls() {
		sv = SysconfigView.this;
		lv = (ListView) findViewById(R.id.sys_lv);
		lv.setOnItemClickListener(this);
		refreshListView();
	}

	private void refreshListView(){

		slist.clear();

		SettingListModel slm = new SettingListModel();
		slm.title = arr[0];
		slm.info = FrameMethod.getIp(fp,this);
		slm.icon_left = R.drawable.spanner_64;
		slm.img_right = R.drawable.img_sys_lvright1;
		slm.setOnClickListener(new SettingListModel.OnClickListener() {
			@Override
			public void onClick(View v) {
				LayoutInflater inflater = LayoutInflater
						.from(sv);
				LinearLayout ll;
				ll = (LinearLayout) inflater.inflate(
						R.layout.alertinput_editview, null);
				final EditText et = (EditText) ll
						.findViewById(R.id.ai_et);
				System.out.println(fp.getSeamurl());
				String ip = "";
				try{
					ip = FrameMethod.getIp(fp, sv);
				}catch(Exception e){
					e.printStackTrace();
					ip = StringHelp.getResSeamUrl(sv);
				}
				et.setText(ip);
				new AlertDialog.Builder(sv)
				.setIcon(R.drawable.epoint2)
				.setTitle(arr[0])
				.setView(ll)
				.setNeutralButton("测试连接", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						String newurl = FrameMethod.newIpUrl(sv, et.getText().toString());
						HashMap param=new HashMap();
						param.put("newurl", newurl);
						Task task = new TestConnectionTask(sv, param);
						MainService.addTask(task);
						try { 
							Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing"); 
							field.setAccessible(true); 
							field.set(dialog, false);
						} catch (Exception e) { 
							e.printStackTrace(); 
						} 
					}

				})
				.setPositiveButton("保存",new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						String newurl = FrameMethod.newIpUrl(SysconfigView.this, et.getText().toString());
						fp.setSeamurl(newurl);
						DBHelp.setConfigValue(SysconfigView.this, ConfigKey.seamurl,newurl);
						ToastHelp.showToast(SysconfigView.this, "IP设置成功");
						AlertHelp.Hide(dialog);
						refreshListView();
					}

				}).setNegativeButton("取消", new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						AlertHelp.Hide(dialog);
					}
				})
				.create().show();
			}
		});
		slist.add(slm);

		if(!DBHelp.getConfigValue(sv, ConfigKey.isLogin).equals("1")){
			MyAdapter adapter = new MyAdapter();
			lv.setAdapter(adapter);
			return;
		}

		slm = new SettingListModel();
		slm.title = "主题设置";
		slm.info = themes[Integer.parseInt(DBHelp.getConfigValue(this, ConfigKey.bgselectedindex).equals("")?"0":DBHelp.getConfigValue(this, ConfigKey.bgselectedindex))];
		slm.icon_left = R.drawable.favorites_add_64;
		slm.img_right = R.drawable.img_sys_lvright1;



		slm.setOnClickListener(new SettingListModel.OnClickListener() {
			@Override
			public void onClick(View v) {
				/*new QuickActionDialog(SysconfigView.this, v, themes, new QuickActionDialog.OnItemClickListener(){

					@Override
					public void onClick(int position) {

						int index = position;

						DBHelp.setConfigValue(SysconfigView.this, ConfigKey.bgselectedindex, String.valueOf(index));

						String bgname = "white";

						if(index==0){
							bgname = "white";
						}
						else if(index==1){
							bgname = "background";
						}

						DBHelp.setConfigValue(SysconfigView.this, ConfigKey.backgroundcolor,bgname);
						fp.setBackgroundcolor(Res.getDrawableInt(bgname));
						setBackground(Res.getDrawableInt(bgname));

						if(bgname.equals("background")){
							topmenu.setBackgroundResource(R.drawable.toolbar_bg);
							top_left_bt.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_menu_back_selectorl));
							top_left_bt.setText("");
							top_right_bt.setBackgroundResource(R.drawable.top_right_btnbg1);
						}
						else{
							topmenu.setBackgroundResource(R.drawable.top_back_image);
							top_left_bt.setBackgroundDrawable(getResources().getDrawable(R.drawable.wb_back_btn));
							top_right_bt.setBackgroundResource(R.drawable.wb_btn);
						}

						refreshListView();

					}

				});*/
				//主题设置
				AlertHelp.showAlertMenu(sv, "主题选择", themes, new DialogInterface.OnClickListener(){

					@Override
					public void onClick(DialogInterface dialog, int which) {
						int index = which;

						DBHelp.setConfigValue(SysconfigView.this, ConfigKey.bgselectedindex, String.valueOf(index));

						String bgname = "white";

						if(index==0){
							bgname = "white";
						}
						else if(index==1){
							bgname = "background";
						}

						DBHelp.setConfigValue(SysconfigView.this, ConfigKey.backgroundcolor,bgname);
						fp.setBackgroundcolor(Res.getDrawableInt(bgname));
						setBackground(Res.getDrawableInt(bgname));

						if(bgname.equals("background")){
							topmenu.setBackgroundResource(R.drawable.toolbar_bg);
							top_left_bt.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_menu_back_selectorl));
							top_left_bt.setText("");
							top_right_bt.setBackgroundResource(R.drawable.top_right_btnbg1);
						}
						else{
							topmenu.setBackgroundResource(R.drawable.top_back_image);
							top_left_bt.setBackgroundDrawable(getResources().getDrawable(R.drawable.wb_back_btn));
							top_right_bt.setBackgroundResource(R.drawable.wb_btn);
						}

						refreshListView();
					}});
			}

		});
		slist.add(slm);

		slm = new SettingListModel();
		slm.title = "自动登录";

		String autologin = DBHelp.getConfigValue(SysconfigView.this, ConfigKey.autologin);
		if(autologin.equals("1")){
			slm.info = "自动登陆";
			slm.img_right = R.drawable.switch_on_normal;
		}
		else{
			slm.info = "自动登陆已取消";
			slm.img_right = R.drawable.switch_off_normal;
		}

		slm.icon_left = R.drawable.key_64;
		slm.setOnClickListener(new SettingListModel.OnClickListener() {
			@Override
			public void onClick(View v) {
				//自动登录
				String autologin = DBHelp.getConfigValue(SysconfigView.this, ConfigKey.autologin);
				if(autologin.equals("1")){
					DBHelp.setConfigValue(SysconfigView.this, ConfigKey.autologin, "0");
				}
				else{
					DBHelp.setConfigValue(SysconfigView.this, ConfigKey.autologin, "1");
				}
				refreshListView();
			}

		});
		slist.add(slm);

		slm = new SettingListModel();
		slm.title = "全屏切换";
		String isfullscreen_db = DBHelp.getConfigValue(SysconfigView.this, ConfigKey.isfullscreen);
		if(isfullscreen_db.equals("1")){
			slm.info = "当前全屏";
			slm.img_right = R.drawable.switch_on_normal;
		}
		else{
			slm.info = "当前非全屏";
			slm.img_right = R.drawable.switch_off_normal;
		}
		slm.icon_left = R.drawable.resize_64;
		slm.setOnClickListener(new SettingListModel.OnClickListener() {
			@Override
			public void onClick(View v) {
				//全屏切换

				String isfullscreen_db = DBHelp.getConfigValue(SysconfigView.this, ConfigKey.isfullscreen);
				if(isfullscreen_db.equals("1")){
					DBHelp.setConfigValue(SysconfigView.this, ConfigKey.isfullscreen, "0");
				}
				else{
					DBHelp.setConfigValue(SysconfigView.this, ConfigKey.isfullscreen, "1");
				}
				setScreenMode();
				refreshListView();
			}

		});
		slist.add(slm);

        slm = new SettingListModel();
        slm.title = "消息提示音";
        String noticemusic = DBHelp.getConfigValue(SysconfigView.this, ConfigKey.noticeMusic);
        if(noticemusic.equals("1")){
            slm.info = "消息提示音开启";
            slm.img_right = R.drawable.switch_on_normal;
        }
        else{
            slm.info = "消息提示音关闭";
            slm.img_right = R.drawable.switch_off_normal;
        }
        slm.icon_left = R.drawable.gear_64;
        slm.setOnClickListener(new SettingListModel.OnClickListener() {
            @Override
            public void onClick(View v) {

                String notice = DBHelp.getConfigValue(SysconfigView.this, ConfigKey.noticeMusic);
                if(notice.equals("1")){
                    DBHelp.setConfigValue(SysconfigView.this, ConfigKey.noticeMusic, "0");
                }
                else{
                    DBHelp.setConfigValue(SysconfigView.this, ConfigKey.noticeMusic, "1");
                }
                refreshListView();
            }

        });
        slist.add(slm);

		slm = new SettingListModel();
		slm.title = "软件初始化";
		slm.info = "软件恢复安装时状态";
		slm.icon_left = R.drawable.info_64;
		slm.img_right = R.drawable.img_sys_lvright1;

		slm.setOnClickListener(new SettingListModel.OnClickListener() {
			@Override
			public void onClick(View v) {
				/*epointDialog = EpointDialog.getDialog(
						sv, 
						"初始化后，软件将恢复到安装时的状态，确定需要进行初始化操作吗？", 
						2, 
						new View.OnClickListener() {
							@Override
							public void onClick(View v) {
								File file = new File(getString(R.string.dbpath)+getString(R.string.dbname));
								file.delete();
								fp.init();
								Intent intent = new Intent(SysconfigView.this,InitView.class);
								startActivity(intent);
								finish();
								epointDialog.dismiss();
							}
						});
				epointDialog.show();	*/
				final SuperDialog sd = new SuperDialog(getContext());
				sd.setPositiveButton("确定", new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						File file = new File(getString(R.string.dbpath)+getString(R.string.dbname));
						file.delete();
						fp.init();
						Intent intent = new Intent(SysconfigView.this,InitView.class);
						startActivity(intent);
						finish();
						sd.dismiss();
					}
				})
				.setNegativeButton("取消", null)
				.setMessage("初始化后，软件将恢复到安装时的状态，确定需要进行初始化操作吗？")
				.setTitle_Epoint("提示")
				.show();
			}

		});
		slist.add(slm);

		slm = new SettingListModel();
		slm.title = "图标排序";
		slm.info = "排列主界面的图标顺序";
		slm.icon_left = R.drawable.img_sys_iconsortsetting;
		slm.img_right = R.drawable.img_sys_lvright1;
		slm.setOnClickListener(new SettingListModel.OnClickListener() {
			@Override
			public void onClick(View v) {
				LayoutInflater inflater = LayoutInflater
						.from(sv);

				//图标排序
				if(!DBHelp.getConfigValue(SysconfigView.this, ConfigKey.isLogin).equals("1")){
					ToastHelp.showToast(SysconfigView.this, "此功能请登录后使用");
					return;
				}

				ScrollView sc = (ScrollView) inflater.inflate(
						R.layout.linearlayout, null);
				final LinearLayout lll = (LinearLayout) sc.findViewById(R.id.ll);

				String positionstr = DBHelp.getConfigValue(sv, ConfigKey.mainviewPositionStr);
				String[] positionstrs = null;
				boolean userconfig = false;
				if(!positionstr.equals("")){
					positionstrs = positionstr.split(";");
					if(positionstrs.length==MainView.titles.length){
						userconfig = true;
					}
				}

				for(int i=0;i<MainView.titles.length;i++){
					LinearLayout ln = new LinearLayout(sv);
					ln.setOrientation(LinearLayout.HORIZONTAL);
					TextView tv = new TextView(sv);
					tv.setText(MainView.titles[i]);
					tv.setWidth(150);
					final Spinner spn = new Spinner(sv);
					ArrayAdapter<String> a = ControlsHelp.getSPAdapter(sv);
					for(int j=0;j<MainView.titles.length;j++){
						a.add((j+1)+"");
					}
					spn.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
							LinearLayout.LayoutParams.WRAP_CONTENT));
					spn.setAdapter(a);

					if(userconfig){
						spn.setSelection(Integer.parseInt(positionstrs[i])-1);
					}

					ln.addView(tv);
					ln.addView(spn);
					lll.addView(ln);

					spn.setOnItemSelectedListener(new OnItemSelectedListener() {

						@Override
						public void onItemSelected(AdapterView<?> parent,
								View view, int position, long id) {
							List<Integer> asf = new ArrayList<Integer>();

							for(int i=0;i<MainView.titles.length;i++){
								asf.add(i);
							}

							Spinner ssp = (Spinner) parent;

							List<Integer> c = new ArrayList<Integer>();
							for(int i=0;i<lll.getChildCount();i++){
								Spinner osp = (Spinner) ((LinearLayout)lll.getChildAt(i)).getChildAt(1);

								if(!c.contains(osp.getSelectedItemPosition())){
									c.add(osp.getSelectedItemPosition());
								}
							}

							for(int i=0;i<c.size();i++){
								asf.remove(c.get(i));
							}

							for(int i=0;i<lll.getChildCount();i++){
								Spinner osp = (Spinner) ((LinearLayout)lll.getChildAt(i)).getChildAt(1);
								if(ssp!=osp){
									if(ssp.getSelectedItemPosition()==osp.getSelectedItemPosition()){
										osp.setSelection(asf.get(0));	
									}
								}
							}
						}

						@Override
						public void onNothingSelected(AdapterView<?> parent) {
						}
					});
				}

				new AlertDialog.Builder(SysconfigView.this)
				.setIcon(R.drawable.epoint2).setTitle(arr[5])
				.setView(sc)
				.setPositiveButton("确定", new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						String positions = "";
						for(int i=0;i<lll.getChildCount();i++){
							Spinner osp = (Spinner) ((LinearLayout)lll.getChildAt(i)).getChildAt(1);
							positions += osp.getSelectedItem().toString()+";";
						}
						DBHelp.setConfigValue(SysconfigView.this, ConfigKey.mainviewPositionStr, positions);
						AlertHelp.Hide(dialog);
						finish();
					}
				})
				.setNegativeButton("取消", new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						AlertHelp.Hide(dialog);
					}
				})
				.setNeutralButton("恢复默认", new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						int[] defaultPosition = MainView.defaultPosition;
						for(int i=0;i<MainView.titles.length;i++){
							Spinner osp = (Spinner) ((LinearLayout)lll.getChildAt(i)).getChildAt(1);
							osp.setSelection(defaultPosition[i]-1);
						}
						AlertHelp.notHide(dialog);
					}
				})
				.create().show();

			}

		});
		//		slist.add(slm);

		slm = new SettingListModel();
		slm.title = "显示类型";
		String displayType = DBHelp.getConfigValue(this, ConfigKey.displayType);

		if(displayType.equals("0")||displayType.equals("")){
			slm.info = "网格";
		}
		else if(displayType.equals("1")){
			slm.info = "分屏";
		}

		slm.icon_left = R.drawable.home_64;
		slm.img_right = R.drawable.img_sys_lvright1;
		slm.setOnClickListener(new SettingListModel.OnClickListener() {
			@Override
			public void onClick(View v) {
				//显示类型
				AlertHelp.showAlertMenu(sv, "显示类型", displayTypeArr, new DialogInterface.OnClickListener(){

					@Override
					public void onClick(DialogInterface dialog, int which) {
						DBHelp.setConfigValue(SysconfigView.this, ConfigKey.displayType, String.valueOf(which));
						refreshListView();
					}});
			}

		});
		slist.add(slm);
		if(getString(R.string.APKType).equals("2")){
			String isFeedBack = PropertiesHelp.getProperty(this, "isAllowQuestionFeedBack");
			if(isFeedBack.equals("1")){
				slm = new SettingListModel();
				slm.title = "问题反馈";
				slm.info = "反馈使用问题";
				slm.icon_left = R.drawable.paper_plane_64;
				slm.img_right = R.drawable.img_sys_lvright1;
				slm.setOnClickListener(new SettingListModel.OnClickListener(){

					@Override
					public void onClick(View v) {

						if(!DBHelp.getConfigValue(SysconfigView.this, ConfigKey.isLogin).equals("1")){
							ToastHelp.showToast(SysconfigView.this, "此功能请登录后使用");
							return;
						}
						Intent it = new Intent(sv, MailSendView.class);
						it.putExtra("viewtitle", "问题反馈");
						it.putExtra("mailtitle", "移动OA问题反馈");
						it.putExtra("sjrnames", "李亚春");
						it.putExtra("sjrguids", "c7a11e9a-797f-46ca-a610-98fd51cd5026");
						it.putExtra("pagetype", 4);
						startActivity(it);

					}
				});
				slist.add(slm);
			}


			slm = new SettingListModel();
			slm.title = "考勤签到";
			if(DBHelp.getConfigValue(this, com.epoint.mobileoa.personalized.epointcompany.config.ConfigKey.QDType).equals("1")){
				slm.info = "方式二";
			}
			else{
				slm.info = "方式一";
			}
			slm.icon_left = R.drawable.img_sys_kqqd;
			slm.img_right = R.drawable.img_sys_lvright1;
			slm.setOnClickListener(new SettingListModel.OnClickListener() {
				@Override
				public void onClick(View v) {

					AlertHelp.showAlertMenu(sv, "定位方式", new String[]{"方式一","方式二"}, new DialogInterface.OnClickListener(){

						@Override
						public void onClick(DialogInterface dialog, int which) {
							DBHelp.setConfigValue(SysconfigView.this, 
									com.epoint.mobileoa.personalized.epointcompany.config.ConfigKey.QDType,which+"");
							refreshListView();
						}});

				}

			});
			//			slist.add(slm);
		}

		slm = new SettingListModel();
		slm.title = "软件更新";
		slm.info = "更新到最新版本";
		slm.icon_left = R.drawable.reload_64;
		slm.img_right = R.drawable.img_sys_lvright1;
		slm.setOnClickListener(new SettingListModel.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent it = new Intent(getContext(), UpdateView.class);
				startActivity(it);
			}
		});

		slist.add(slm);

		if(DBHelp.getConfigValue(this, ConfigKey.isAdmin).equals("1"))
		{
			slm = new SettingListModel();
			slm.title = "系统日志";
			slm.info = "查看系统使用日志";
			slm.icon_left = R.drawable.zoom_in_64;
			slm.img_right = R.drawable.img_sys_lvright1;
			slm.setOnClickListener(new SettingListModel.OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent it = new Intent(getContext(), StatisticsMain.class);
					startActivity(it);
				}
			});
			slist.add(slm);
		}
		MyAdapter adapter = new MyAdapter();
		lv.setAdapter(adapter);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view,
			int position, long id) {
		slist.get(position).executeOnClickListener(view);
	}

	@Override
	public void refresh(Object... param) {
		if(param[0].toString().equals(MainService.NORMAL)){
			if(param[1].equals("true")){
				ToastHelp.showToast(this, "连接成功", 1000);
				MusicHelp.playMusic(SysconfigView.this, "c_success.mid");
			}
			else{
				ToastHelp.showToast(this, "连接失败", 1000);
				MusicHelp.playMusic(SysconfigView.this, "c_failure.mid");
			}
		}
	}

	@Override
	public int getLayoutInt() {
		return R.layout.sysconfig;
	}


	@Override
	public String setTitle() {
		return getString(R.string.xtsz);
	}

	public class ViewHolder {
		public ImageView ivLeft;
		public ImageView ivRight;
		public TextView tvTop;
		public TextView tvBottom;
	}

	class MyAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			return slist.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				holder = new ViewHolder();
				LayoutInflater mInflater = LayoutInflater.from(SysconfigView.this);
				convertView = mInflater.inflate(R.layout.lv_setting, null);
				holder.ivLeft = (ImageView) convertView
						.findViewById(R.id.ivIconLeft);
				holder.ivRight = (ImageView) convertView
						.findViewById(R.id.ivImgRight);
				holder.tvTop = (TextView) convertView
						.findViewById(R.id.tvTitle);
				holder.tvBottom = (TextView) convertView
						.findViewById(R.id.tvInfo);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			SettingListModel slm = slist.get(position);

			holder.ivLeft.setImageResource(slm.icon_left);
			//			holder.ivLeft.setVisibility(View.GONE);
			holder.ivRight.setImageResource(slm.img_right);
			holder.tvTop.setText(slm.title);

			setTextViewFontColor(holder.tvTop);

			holder.tvBottom.setText(slm.info);
			return convertView;
		}

	}

	@Override
	public void refreshForNewTask(int TaskId,Object... param) {
	}
}
